<?php


use Illuminate\Support\Facades\Auth;
use Overtrue\Wechat\Payment\Notify;
class WeixinController extends BaseController{
	
	/**
	 * 接受微信的授权
	 * @return string
	 */
	public function receiveAuthed(){
	
		$appId = Config::get("mao.wxpay.app_id");
		$appKey = Config::get("mao.wxpay.app_key");
		$auth = new Overtrue\Wechat\Auth($appId,$appKey);
		$wxuser = $auth->user();
		//Log::error("receive -authed");
		//用户取消授权了，则直接返回
		if (empty($wxuser)){
			return "invalid request";
		} else {
			//Log::error($wxuser);
			if (!$wxuser->has("openid")){
				//需要重定向到form
				Log::error("user authed ,but not found openid");
				//跳转用户订单列表页面
				return Redirect::to('user/order-list');
			}else {
				/*
				
				$user = User::find($userId);
				$user->open_id = 
					
				$user->save();*/
				$userId = "aaaa".Auth::id() ."bbbb";
				Session::flash($userId, $wxuser->get("openid"));
				$original = Session::get('original-url','user/order-list');
				//重定向到
				return Redirect::to($original);
			}
		}
		
	}
	
	/**
	 * 微信支付成功通知页面
	 */
	public function payNofity(){
		$notify = new Notify(
				Config::get("mao.wxpay.app_id"),
				Config::get("mao.wxpay.app_key"),
				Config::get("mao.wxpay.mch_id"),
				Config::get("mao.wxpay.mch_key")
		);
		
		$transaction = $notify->verify();
		
		if (!$transaction) {
			$notify->reply('FAIL', 'verify transaction error');
		} else {
			//更新订单状态
// 			out_trade_no
			$orderId = $transaction->get("out_trade_no");
			$order = Order::where("status",'=',0)->where("id","=",$orderId)->first();
			if (!empty($order)){
				//更新订单的状态，并且设置为微信支付
				$order->update(array('pay_type'=>2,'status'=>1));
				//邮件通知
				Mail::queue('emails.order_notify', array("id"=>$orderId), function($message){
					$message->to('info@maggiemaostudio.com', 'Maggiemaostudio')->subject('新订单通知!');
				});
			}
		}
		
		// var_dump($transaction);
		
		return $notify->reply();
	}
}

?>